<template>
	<view class="map-container">
		<map id="myMap" class="map" :latitude="latitude" :longitude="longitude" :markers="markers" :scale="scale"
			show-location @regionchange="e => handleMapEvent(e, 'regionchange')" @tap="e => handleMapEvent(e, 'tap')"
			key="mapKey"></map>

		<!-- 搜索框 -->
		<view class="search-box">
			<view class="input-group">
				<input v-model="searchKeyword" class="input" placeholder="搜索地点、公交、地铁" @input="handleSearch" />
				<button class="search-btn" @tap="searchNearby">搜索</button>
			</view>
			<!-- 搜索建议列表 -->
			<scroll-view v-if="suggestions.length > 0" class="suggestions-list" scroll-y>
				<view v-for="(item, index) in suggestions" :key="index" class="suggestion-item"
					@tap="selectSuggestion(item)">
					<text class="suggestion-title">{{item.title}}</text>
					<text class="suggestion-address">{{item.address}}</text>
				</view>
			</scroll-view>
		</view>

		<!-- 位置信息展示 -->
		<view v-if="locationInfo" class="location-info">
			<view class="info-header">
				<text class="info-title">{{locationInfo.title || '当前位置'}}</text>
				<text class="info-address">{{locationInfo.address}}</text>
			</view>
		</view>

		<view class="controls">
			<button class="control-btn" @tap="moveToLocation">定位</button>
			<button class="control-btn" @tap="changeScale(1)">放大</button>
			<button class="control-btn" @tap="changeScale(-1)">缩小</button>
		</view>
	</view>
</template>

<script>
	import QQMapWX from '../../util/qqmap-wx-jssdk.js';

	export default {
		data() {
			return {
				latitude: '',
				longitude: '',
				scale: 14,
				markers: [],
				qqmapsdk: null,
				searchKeyword: '',
				suggestions: [],
				locationInfo: null,
				searchTimeout: null,
				mapKey: Date.now(),
				currentLatitude: null,
				currentLongitude: null
			}
		},
		onLoad() {
			// 初始化地图SDK
			this.qqmapsdk = new QQMapWX({
				key: '2JRBZ-UEILT-ANBXA-LMHFJ-4F5V6-P5FGW',
				baseUrl: 'https://apis.map.qq.com/ws/',
			});

			// 尝试获取当前位置
			this.getLocation();
		},
		methods: {
			// 获取当前位置
			getLocation() {
				uni.showLoading({
					title: '定位中...'
				});
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log(res)
						uni.hideLoading();
						// this.latitude = res.latitude;
						// this.longitude = res.longitude;
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.latitude = 39.009;
						this.longitude =116.245;

						this.currentLatitude = res.latitude;
						this.currentLongitude = res.longitude;
						this.reverseGeocode(res.latitude, res.longitude);

						// 定位成功后自动移动视角
						this.moveToLocation();
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('获取位置失败:', err);
						uni.showToast({
							title: '获取位置失败，请检查权限设置',
							icon: 'none'
						});
						this.updateMarkers(this.latitude, this.longitude, '默认位置');
					}
				});
			},

			// 更新标记点
			updateMarkers(lat, lng, title) {
				this.markers = [{
					id: 0,
					title: title,
					latitude: lat,
					longitude: lng,
					width: 32,
					height: 32,
					iconPath: 'http://121.36.197.175:19000/test/marker.png',
					callout: {
						content: title || `${lat.toFixed(6)},${lng.toFixed(6)}`,
						color: '#000',
						fontSize: 14,
						borderRadius: 4,
						padding: 8,
						display: 'ALWAYS'
					}
				}];
			},

			// 移动到指定位置
			moveToLocation() {
				if (!this.currentLatitude || !this.currentLongitude) {
					this.getLocation(); // 如果没有定位信息，重新获取
					return;
				}

				this.latitude = this.currentLatitude;
				this.longitude = this.currentLongitude;

				// 添加：更新底部位置展示
				this.reverseGeocode(this.currentLatitude, this.currentLongitude);

				this.$nextTick(() => {
					const mapCtx = uni.createMapContext('myMap', this);
					mapCtx.moveToLocation({
						latitude: this.currentLatitude,
						longitude: this.currentLongitude,
						success: () => {
							console.log('回到当前位置');
						},
						fail: (err) => {
							console.error('moveToLocation 失败:', err);
						}
					});
				});
			},

			// 搜索建议
			handleSearch() {
				if (this.searchTimeout) {
					clearTimeout(this.searchTimeout);
				}

				this.searchTimeout = setTimeout(() => {
					if (!this.searchKeyword) {
						this.suggestions = [];
						return;
					}

					this.qqmapsdk.getSuggestion({
						keyword: this.searchKeyword,
						region: '全国',
						success: (res) => {
							this.suggestions = res.data;
						},
						fail: (err) => {
							console.error('获取搜索建议失败:', err);
						}
					});
				}, 300);
			},

			// 选择搜索建议
			selectSuggestion(item) {
				this.searchKeyword = item.title;
				this.suggestions = []; // 清空建议列表

				// 更新地图位置
				this.latitude = item.location.lat;
				this.longitude = item.location.lng;

				// 显示选中地点的信息
				// this.locationInfo = {
				// 	title: item.title,
				// 	address: item.address
				// };
				this.reverseGeocode(item.location.lat, item.location.lng);

				// 更新标记点
				this.updateMarkers(item.location.lat, item.location.lng, item.title);

				// 聚焦到选中地点
				this.$nextTick(() => {
					const mapCtx = uni.createMapContext('myMap', this);
					mapCtx.moveToLocation();
				});
			},

			// 搜索周边
			searchNearby() {
				if (!this.searchKeyword) {
					uni.showToast({
						title: '请输入搜索关键词',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '搜索中...',
					mask: true
				});

				this.qqmapsdk.search({
					keyword: this.searchKeyword,
					location: `${this.latitude},${this.longitude}`,
					success: (res) => {
						uni.hideLoading();

						if (!res.data || res.data.length === 0) {
							uni.showToast({
								title: '未找到相关地点',
								icon: 'none'
							});
							return;
						}

						// 更新标记点
						this.markers = res.data.map((item, index) => ({
							id: index + 1, // 避免和当前位置的标记点冲突（id=0）
							title: item.title,
							latitude: item.location.lat,
							longitude: item.location.lng,
							width: 24,
							height: 24,
							iconPath: 'http://121.36.197.175:19000/test/marker.png', // 确保路径正确
							callout: {
								content: item.title,
								color: '#000',
								fontSize: 14,
								borderRadius: 4,
								padding: 8,
								display: 'ALWAYS'
							}
						}));

						// 默认聚焦到第一个搜索结果
						if (res.data.length > 0) {
							this.latitude = res.data[0].location.lat;
							this.longitude = res.data[0].location.lng;
							this.locationInfo = {
								title: res.data[0].title,
								address: res.data[0].address
							};
						}
					},
					fail: (err) => {
						uni.hideLoading();
						console.error('搜索失败:', err);
						uni.showToast({
							title: '搜索失败，请重试',
							icon: 'none'
						});
					}
				});
			},

			// 逆地址解析
			reverseGeocode(lat, lng) {
				// 开发环境下使用JSONP方式
				if (process.env.NODE_ENV === 'development') {
					this.qqmapsdk = new QQMapWX({
						key: '2JRBZ-UEILT-ANBXA-LMHFJ-4F5V6-P5FGW',
						baseUrl: 'https://apis.map.qq.com/ws/',
						jsonp: true
					});
				}

				this.qqmapsdk.reverseGeocoder({
					location: {
						latitude: lat,
						longitude: lng
					},
					success: (res) => {
						const result = res.result;
						this.locationInfo = {
							title: result.formatted_addresses?.recommend || '当前位置',
							address: result.address || '未知地址'
						};
						this.updateMarkers(lat, lng, this.locationInfo.title);
						// this.moveToLocation();
					},
					fail: (err) => {
						console.error('逆地址解析失败:', err);
						// 失败时使用原始坐标
						this.locationInfo = {
							title: '当前位置',
							address: `${lat.toFixed(6)}, ${lng.toFixed(6)}`
						};
						this.updateMarkers(lat, lng, '当前位置');
					}
				});
			},

			// 地图缩放
			changeScale(delta) {
				const next = this.scale + delta;
				if (next >= 3 && next <= 20) {
					this.scale = next;
				}
			},

			// 地图事件处理
			handleMapEvent(e, type) {
				console.log(type, e);

				if (type === 'tap') {
					const {
						latitude,
						longitude
					} = e.detail;

					this.latitude = latitude;
					this.longitude = longitude;

					// 显示用户点击位置的地址信息
					this.reverseGeocode(latitude, longitude);
				}
			}
		}
	}
</script>

<style>
	.map-container {
		position: relative;
		width: 100%;
		height: 100vh;
	}

	.map {
		width: 100%;
		height: 100%;
	}

	.controls {
		position: absolute;
		top: 50%;
		right: 30rpx;
		transform: translateY(-50%);
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		z-index: 99;
	}

	.control-btn {
		padding: 15rpx 30rpx;
		background-color: #ffffff;
		border: 1px solid #dddddd;
		border-radius: 30rpx;
		font-size: 28rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		min-width: 100rpx;
		text-align: center;
	}

	/* 添加地址解析表单样式 */
	.search-box {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		right: 20rpx;
		z-index: 100;
	}

	.input-group {
		display: flex;
		background-color: #ffffff;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		overflow: hidden;
	}

	.input {
		flex: 1;
		height: 80rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
	}

	.search-btn {
		width: 150rpx;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #007AFF;
		color: #ffffff;
		font-size: 28rpx;
		text-align: center;
		border-radius: 0;
	}

	/* 搜索建议列表样式 */
	.suggestions-list {
		margin-top: 2rpx;
		max-height: 400rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}

	.suggestion-item {
		padding: 20rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.suggestion-item:last-child {
		border-bottom: none;
	}

	.suggestion-title {
		font-size: 28rpx;
		color: #333333;
		display: block;
	}

	.suggestion-address {
		font-size: 24rpx;
		color: #666666;
		display: block;
		margin-top: 6rpx;
	}

	/* 位置信息展示样式 */
	.location-info {
		position: absolute;
		bottom: 120rpx;
		left: 20rpx;
		right: 20rpx;
		background-color: #ffffff;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		padding: 20rpx;
	}

	.info-header {
		display: flex;
		flex-direction: column;
	}

	.info-title {
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
	}

	.info-address {
		font-size: 26rpx;
		color: #666666;
		margin-top: 10rpx;
	}
</style>
